﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Web.Security;
using System.Globalization;

namespace TravelSite.Controls
{
    public partial class SalesForm : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
            }

        }

        private void LoadCombo()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                ddlCountryId.DataSource = repo.CountriesCombo(false, false);
                ddlCountryId.DataBind();
                ddlCountryId.SelectedValue = "1";                
            }

            LoadStates();

            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                ddlAgentId.DataSource = repo.AgentsCombo(false);
                ddlAgentId.DataBind();
            }

            ddlExpYear.Items.Add(new ListItem("(year)", "-1"));
            ddlExpYear.SelectedValue = "-1";
            for (int i = DateTime.Now.Year; i < DateTime.Now.Year + 10; i++)
                ddlExpYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }

        private void LoadStates()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                ddlStateId.DataSource = repo.StatesCombo(false, true, Convert.ToInt32(ddlCountryId.SelectedValue));
                ddlStateId.DataBind();
            }

            ddlStateId.Items[0].Text = ddlCountryId.SelectedValue == "2" ? "(Select Province)" : "(Select State)";
            lblState.Text = ddlCountryId.SelectedValue == "2" ? "Province" : "State";
            lblZipCode.Text = (ddlCountryId.SelectedValue == "2" ? "Postal" : "Zip") + " Code";
        }

        protected void upSalesForm_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request["__EVENTTARGET"]))
                if (Request["__EVENTTARGET"] != upSalesForm.ClientID)
                    return;

            if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]))
            {
                hdId.Text = Request["__EVENTARGUMENT"];

                if (hdId.Text != "-1")
                {
                    using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
                    {
                        Contact itm = repo.Find(Convert.ToInt32(hdId.Text));

                        if (itm.SalesFormDate.HasValue)
                            txtSalesFormDate.Text = itm.SalesFormDate.Value.ToString("d", new CultureInfo("en-US"));
                        else
                            txtSalesFormDate.Text = DateTime.Today.ToString("d", new CultureInfo("en-US"));
                        txtSalesFormList.Text = itm.SalesFormList;

                        if (itm.SalesFormManagerPrice.HasValue)
                            txtSalesFormManagerPrice.Text = itm.SalesFormManagerPrice.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtSalesFormManagerPrice.Text = "";
                        if (itm.SalesFormProcessingFee.HasValue)
                            txtSalesFormProcessingFee.Text = itm.SalesFormProcessingFee.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtSalesFormProcessingFee.Text = "20";
                        if (itm.SalesFormTotal.HasValue)
                            txtSalesFormTotal.Text = itm.SalesFormTotal.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtSalesFormTotal.Text = "";

                        txtSalesFormEmailed.Text = itm.SalesFormEmailed;
                        ddlAgentId.SelectedValue = itm.AgentId.ToString();
                        txtSalesFormCloser.Text = itm.SalesFormCloser;

                        rbSalesFormMarried.Checked = true;
                        if (itm.SalesFormMarriedType == "C")
                            rbSalesFormCoHab.Checked = true;
                        else if (itm.SalesFormMarriedType == "S")
                            rbSalesFormSingle.Checked = true;

                        ddlSalesFormCoHabMatchingIds.SelectedValue = "1";
                        ddlSalesFormSingleGender.SelectedValue = "M";
                        ddlSalesFormSingleOwnTimeshare.SelectedValue = "0";
                        txtSalesFormSingleOwnTimeshareName.Text = "";
                        if (itm.SalesFormMarriedType == "M")
                            rbSalesFormMarried.Checked = true;
                        else if (itm.SalesFormMarriedType == "C")
                        {
                            rbSalesFormCoHab.Checked = true;
                            ddlSalesFormCoHabMatchingIds.SelectedValue = itm.SalesFormCoHabMatchingIds ? "1" : "0";
                        }
                        else if (itm.SalesFormMarriedType == "S")
                        {
                            rbSalesFormSingle.Checked = true;
                            ddlSalesFormSingleGender.SelectedValue = itm.SalesFormSingleGender;
                            ddlSalesFormSingleOwnTimeshare.SelectedValue = itm.SalesFormSingleOwnTimeshare ? "1" : "0";
                            if (itm.SalesFormSingleOwnTimeshare)
                                txtSalesFormSingleOwnTimeshareName.Text = itm.SalesFormSingleOwnTimeshareName;
                        }

                        if (itm.SalesFormIncome.HasValue)
                            txtSalesFormIncome.Text = itm.SalesFormIncome.Value.ToString("N", new CultureInfo("en-US"));
                        else
                            txtSalesFormIncome.Text = "";
                        if (itm.SalesFormAge.HasValue)
                            cbSalesFormAge.Checked = itm.SalesFormAge.Value.ToString() == "1";
                        else
                            cbSalesFormAge.Checked = false;

                        txtFirstName.Text = itm.FirstName;
                        txtLastName.Text = itm.LastName;

                        txtPartnerFirstName.Text = itm.PartnerFirstName;
                        txtPartnerLastName.Text = itm.PartnerLastName;

                        txtSalesFormBillingAddress1.Text = itm.Address1;
                        txtSalesFormBillingAddress2.Text = itm.Address2;
                        ddlCountryId.SelectedValue = itm.CountryId.ToString();
                        LoadStates();
                        ddlStateId.SelectedValue = (itm.StateId ?? -1).ToString();

                        txtZip.Text = itm.Zip;
                        txtCity.Text = itm.City;

                        txtEmail.Text = itm.Email;
                        txtMPhone.Text = itm.MPhone;
                        txtWPhone.Text = itm.WPhone;

                        ddlSalesFormMajorCreditCard.SelectedValue = itm.SalesFormMajorCreditCard ? "1" : "0";
                        txtSalesFormNameOnCard.Text = "";
                        ddlExpMonth.SelectedIndex = 0;
                        ddlExpYear.SelectedIndex = 0;                        
                        txtSalesFormCardCVV.Text = "";
                        txtBillingAddress.Text = "";
                        rbSalesFormCardTypeVisa.Checked = true;

                        if (itm.SalesFormMajorCreditCard)
                        {
                            txtSalesFormNameOnCard.Text = itm.SalesFormNameOnCard;
                            if (itm.SalesFormCardExp.HasValue)
                            {
                                ddlExpMonth.SelectedIndex = itm.SalesFormCardExp.Value.Month;
                                ddlExpYear.SelectedValue = itm.SalesFormCardExp.Value.Year.ToString();
                            }
                            txtSalesFormCardNo.Text = itm.SalesFormCardNo;
                            txtSalesFormCardCVV.Text = itm.SalesFormCardCVV;
                            txtBillingAddress.Text = itm.SalesFormBillingAddress;

                            if (itm.SalesFormCardType == "visa")
                                rbSalesFormCardTypeVisa.Checked = true;
                            else if (itm.SalesFormCardType == "master")
                                rbSalesFormCardTypeMaster.Checked = true;
                            else if (itm.SalesFormCardType == "discover")
                                rbSalesFormCardTypeDiscover.Checked = true;
                            else if (itm.SalesFormCardType == "american")
                                rbSalesFormCardTypeAmerican.Checked = true;
                        }

                        chbSalesFormDestinationLasVegas.Checked = itm.SalesFormDestinationLasVegas;
                        chbSalesFormDestinationOpen.Checked = itm.SalesFormDestinationOpen;
                        chbSalesFormDestination4days3nights.Checked = itm.SalesFormDestination4days3nights;
                        chbSalesFormDestination3days2nights.Checked = itm.SalesFormDestination3days2nights;
                        txtSalesFormBonus1.Text = itm.SalesFormBonus1;
                        txtSalesFormBonus2.Text = itm.SalesFormBonus2;
                        txtSalesFormBonus3.Text = itm.SalesFormBonus3;
                        
                        rbSalesFormOwnTimeshare.Checked = itm.SalesFormOwnTimeshare;
                        rbSalesFormOwnTimeshareNo.Checked = !itm.SalesFormOwnTimeshare;
                        txtSalesFormOwnTimeshareName.Text = "";
                        txtSalesFormOwnTimeshareTotalTix.Text = "";
                        txtSalesFormOwnTimeshareNotes.Text = "";

                        if (itm.SalesFormOwnTimeshare)
                        {
                            txtSalesFormOwnTimeshareName.Text = itm.SalesFormOwnTimeshareName;
                            txtSalesFormOwnTimeshareTotalTix.Text = itm.SalesFormOwnTimeshareTotalTix;
                            txtSalesFormOwnTimeshareNotes.Text = itm.SalesFormOwnTimeshareNotes;
                        }

                        txtSalesFormVerifiedBy.Text = itm.SalesFormVerifiedBy;
                        txtSalesFormMerchant.Text = itm.SalesFormMerchant;
                        txtSalesFormConfirmation.Text = itm.SalesFormConfirmation;
                        txtSalesFormCCAuth.Text = itm.SalesFormCCAuth;
                        txtSalesFormTime.Text = itm.SalesFormTime;

                        txtGift1.Text = itm.Gift1;
                        txtGift2.Text = itm.Gift2;
                        txtGift3.Text = itm.Gift3;
                        txtGift4.Text = itm.Gift4;
                        txtGift5.Text = itm.Gift5;
                        txtGift6.Text = itm.Gift6;
                        txtGift7.Text = itm.Gift7;
                        txtGift8.Text = itm.Gift8;
                    }
                }
                else
                {
                    using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
                    {
                        Contact itm = repo.GetLastUpdatedSalesForm();
                        if (itm != null)
                        {
                            txtGift1.Text = itm.Gift1;
                            txtGift2.Text = itm.Gift2;
                            txtGift3.Text = itm.Gift3;
                            txtGift4.Text = itm.Gift4;
                            txtGift5.Text = itm.Gift5;
                            txtGift6.Text = itm.Gift6;
                            txtGift7.Text = itm.Gift7;
                            txtGift8.Text = itm.Gift8;
                        }
                        else
                        {
                            txtGift1.Text = "Dinner & Show for 2";
                            txtGift2.Text = "Casa di Amore w/ Limo Ride";
                            txtGift3.Text = "Vow Renewal";
                            txtGift4.Text = "$ of Promotional Slot Play";
                            txtGift5.Text = "$ Dining Voucher";
                            txtGift6.Text = "$ Complimentary Show Tickets";
                            txtGift7.Text = "$500 Travelers Credit";
                            txtGift8.Text = "Buddy Pass";
                        }
                    }

                    txtSalesFormDate.Text = DateTime.Today.ToString("d", new CultureInfo("en-US"));
                    txtSalesFormList.Text = "";

                    txtSalesFormManagerPrice.Text = "";
                    txtSalesFormProcessingFee.Text = "20";
                    txtSalesFormTotal.Text = "";

                    txtSalesFormEmailed.Text = "";
                    txtSalesFormCloser.Text = "";

                    rbSalesFormMarried.Checked = true;
                    
                    ddlSalesFormCoHabMatchingIds.SelectedValue = "1";
                    ddlSalesFormSingleGender.SelectedValue = "M";
                    ddlSalesFormSingleOwnTimeshare.SelectedValue = "0";
                    txtSalesFormSingleOwnTimeshareName.Text = "";
                    
                    txtSalesFormIncome.Text = "";
                    cbSalesFormAge.Checked = false;

                    txtFirstName.Text = "";
                    txtLastName.Text = "";

                    txtPartnerFirstName.Text = "";
                    txtPartnerLastName.Text = "";

                    txtSalesFormBillingAddress1.Text = "";
                    txtSalesFormBillingAddress2.Text = "";
                    ddlCountryId.SelectedValue = "1";
                    LoadStates();
                    
                    txtZip.Text = "";
                    txtCity.Text = "";

                    txtEmail.Text = "";
                    txtMPhone.Text = "";
                    txtWPhone.Text = "";

                    ddlSalesFormMajorCreditCard.SelectedValue = "0";
                    txtSalesFormNameOnCard.Text = "";
                    ddlExpMonth.SelectedIndex = 0;
                    ddlExpYear.SelectedIndex = 0;
                    txtSalesFormCardCVV.Text = "";
                    txtBillingAddress.Text = "";
                    rbSalesFormCardTypeVisa.Checked = true;

                    chbSalesFormDestinationLasVegas.Checked = false;
                    chbSalesFormDestinationOpen.Checked = false;
                    chbSalesFormDestination4days3nights.Checked = false;
                    chbSalesFormDestination3days2nights.Checked = false;
                    txtSalesFormBonus1.Text = "";
                    txtSalesFormBonus2.Text = "";
                    txtSalesFormBonus3.Text = "";

                    rbSalesFormOwnTimeshare.Checked = false;
                    rbSalesFormOwnTimeshareNo.Checked = true;
                    txtSalesFormOwnTimeshareName.Text = "";
                    txtSalesFormOwnTimeshareTotalTix.Text = "";
                    txtSalesFormOwnTimeshareNotes.Text = "";
                    
                    txtSalesFormVerifiedBy.Text = "";
                    txtSalesFormMerchant.Text = "";
                    txtSalesFormConfirmation.Text = "";
                    txtSalesFormCCAuth.Text = "";
                    txtSalesFormTime.Text = "";

                    if (Roles.IsUserInRole("agent"))
                    {
                        ddlAgentId.SelectedValue = (Page as BasePage).CurrentUserId.ToString();
                    }
                }

                ddlAgentId.Enabled = !Roles.IsUserInRole("agent");

                rbSalesFormMarried.Attributes.Add("onclick", "javascript:SalesFormMarriedClick();");
                rbSalesFormCoHab.Attributes.Add("onclick", "javascript:SalesFormMarriedClick();");
                rbSalesFormSingle.Attributes.Add("onclick", "javascript:SalesFormMarriedClick();");

                ddlSalesFormSingleGender.Attributes.Add("onclick", "javascript:SalesFormSingleGenderClick();");
                ddlSalesFormSingleOwnTimeshare.Attributes.Add("onclick", "javascript:SalesFormSingleOwnTimeshareClick();");

                ddlSalesFormMajorCreditCard.Attributes.Add("onclick", "javascript:SalesFormMajorCreditCardClick();");

                rbSalesFormOwnTimeshare.Attributes.Add("onclick", "javascript:SalesFormOwnTimeshareClick();");
                rbSalesFormOwnTimeshareNo.Attributes.Add("onclick", "javascript:SalesFormOwnTimeshareClick();");
                
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowSalesForm", "openSalesForm();", true);
            }
        }

        protected void ddlCountry_SelectedIndexChanged(Object sender, EventArgs e)
        {
            LoadStates();
        }

        protected void btnSaveSalesForm_Click(object sender, EventArgs e)
        {
            int? newContactId = null;

            DateTime? salesFormDate = null;
            try
            {
                if (!string.IsNullOrEmpty(txtSalesFormDate.Text))
                    salesFormDate = DateTime.ParseExact(txtSalesFormDate.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Date not valid!');", true);
                return;
            }

            decimal? salesFormManagerPrice = null;
            try
            {
                if (!string.IsNullOrEmpty(txtSalesFormManagerPrice.Text))
                    salesFormManagerPrice = decimal.Parse(txtSalesFormManagerPrice.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Manager price not valid!');", true);
                return;
            }

            decimal? salesFormProcessingFee = null;
            try
            {
                if (!string.IsNullOrEmpty(txtSalesFormProcessingFee.Text))
                    salesFormProcessingFee = decimal.Parse(txtSalesFormProcessingFee.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Manager price not valid!');", true);
                return;
            }

            decimal? salesFormTotal = null;
            try
            {
                if (!string.IsNullOrEmpty(txtSalesFormTotal.Text))
                    salesFormTotal = decimal.Parse(txtSalesFormTotal.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Total not valid!');", true);
                return;
            }

            decimal? salesFormIncome = null;
            try
            {
                if (!string.IsNullOrEmpty(txtSalesFormIncome.Text))
                    salesFormIncome = decimal.Parse(txtSalesFormIncome.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Income not valid!');", true);
                return;
            }

            int salesFormAge = cbSalesFormAge.Checked ? 1 : 0;

            DateTime? salesFormCardExp = null;
            try
            {
                if (ddlExpMonth.SelectedIndex > 0 && ddlExpYear.SelectedIndex > 0)
                {
                    salesFormCardExp = new DateTime(int.Parse(ddlExpYear.SelectedValue), ddlExpMonth.SelectedIndex, 1);
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "alert('Card Exp date not valid!');", true);
                return;
            }

            Contact itm = new Contact();
                        
            itm.SalesFormDate = salesFormDate;
            itm.SalesFormList = txtSalesFormList.Text;

            itm.SalesFormManagerPrice = salesFormManagerPrice;
            itm.SalesFormProcessingFee = salesFormProcessingFee;
            itm.SalesFormTotal = salesFormTotal;

            itm.SalesFormEmailed = txtSalesFormEmailed.Text;
            itm.AgentId = Convert.ToInt32(ddlAgentId.SelectedValue);
            itm.SalesFormCloser = txtSalesFormCloser.Text;

            itm.SalesFormMarriedType = "M";
            itm.SalesFormCoHabMatchingIds = true;
            itm.SalesFormSingleGender = "M";
            itm.SalesFormSingleOwnTimeshare = false;
            itm.SalesFormSingleOwnTimeshareName = "";
            if (rbSalesFormCoHab.Checked)
            {
                itm.SalesFormMarriedType = "C";
                itm.SalesFormCoHabMatchingIds = ddlSalesFormCoHabMatchingIds.SelectedValue == "1" ? true : false;
            }
            else if (rbSalesFormSingle.Checked)
            {
                itm.SalesFormMarriedType = "S";
                itm.SalesFormSingleGender = ddlSalesFormSingleGender.SelectedValue;
                itm.SalesFormSingleOwnTimeshare = ddlSalesFormSingleOwnTimeshare.SelectedValue == "1" ? true : false;
                if (itm.SalesFormSingleOwnTimeshare)
                    itm.SalesFormSingleOwnTimeshareName = txtSalesFormSingleOwnTimeshareName.Text;
            }

            itm.SalesFormIncome = salesFormIncome;
            itm.SalesFormAge = salesFormAge;

            itm.FirstName = txtFirstName.Text;
            itm.LastName = txtLastName.Text;

            itm.PartnerFirstName = txtPartnerFirstName.Text;
            itm.PartnerLastName = txtPartnerLastName.Text;

            itm.Address1 = txtSalesFormBillingAddress1.Text;
            itm.Address2 = txtSalesFormBillingAddress2.Text;

            itm.CountryId = Convert.ToInt32(ddlCountryId.SelectedValue);
            itm.StateId = ddlStateId.SelectedValue == "-1" ? null : (int?)Convert.ToInt32(ddlStateId.SelectedValue);
            itm.Zip = txtZip.Text;
            itm.City = txtCity.Text;

            itm.Email = txtEmail.Text;
            itm.WPhone = txtWPhone.Text;
            itm.MPhone = txtMPhone.Text;

            itm.SalesFormMajorCreditCard = ddlSalesFormMajorCreditCard.SelectedValue == "1" ? true : false;
            itm.SalesFormNameOnCard = "";
            itm.SalesFormCardExp = null;
            itm.SalesFormCardNo = "";
            itm.SalesFormCardCVV = "";
            itm.SalesFormCardType = "";
            if (itm.SalesFormMajorCreditCard)
            {
                itm.SalesFormNameOnCard = txtSalesFormNameOnCard.Text;
                itm.SalesFormCardExp = salesFormCardExp;
                itm.SalesFormCardNo = txtSalesFormCardNo.Text;
                itm.SalesFormCardCVV = txtSalesFormCardCVV.Text;
                itm.SalesFormBillingAddress = txtBillingAddress.Text;

                if (rbSalesFormCardTypeVisa.Checked)
                    itm.SalesFormCardType = "visa";
                else if (rbSalesFormCardTypeMaster.Checked)
                    itm.SalesFormCardType = "master";
                else if (rbSalesFormCardTypeDiscover.Checked)
                    itm.SalesFormCardType = "discover";
                else if (rbSalesFormCardTypeAmerican.Checked)
                    itm.SalesFormCardType = "american";
            }
            
            itm.SalesFormDestinationLasVegas = chbSalesFormDestinationLasVegas.Checked;
            itm.SalesFormDestinationOpen = chbSalesFormDestinationOpen.Checked;
            itm.SalesFormDestination4days3nights = chbSalesFormDestination4days3nights.Checked;
            itm.SalesFormDestination3days2nights = chbSalesFormDestination3days2nights.Checked;
            itm.SalesFormBonus1 = txtSalesFormBonus1.Text;
            itm.SalesFormBonus2 = txtSalesFormBonus2.Text;
            itm.SalesFormBonus3 = txtSalesFormBonus3.Text;

            itm.SalesFormOwnTimeshare = rbSalesFormOwnTimeshare.Checked;
            itm.SalesFormOwnTimeshareName = "";
            itm.SalesFormOwnTimeshareTotalTix = "";
            itm.SalesFormOwnTimeshareNotes = "";

            if (itm.SalesFormOwnTimeshare)
            {
                itm.SalesFormOwnTimeshareName = txtSalesFormOwnTimeshareName.Text;
                itm.SalesFormOwnTimeshareTotalTix = txtSalesFormOwnTimeshareTotalTix.Text;
                itm.SalesFormOwnTimeshareNotes = txtSalesFormOwnTimeshareNotes.Text;
            }

            itm.SalesFormVerifiedBy = txtSalesFormVerifiedBy.Text;
            itm.SalesFormMerchant = txtSalesFormMerchant.Text;
            itm.SalesFormConfirmation = txtSalesFormConfirmation.Text;
            itm.SalesFormCCAuth = txtSalesFormCCAuth.Text;
            itm.SalesFormTime = txtSalesFormTime.Text;

            itm.Gift1 = txtGift1.Text;
            itm.Gift2 = txtGift2.Text;
            itm.Gift3 = txtGift3.Text;
            itm.Gift4 = txtGift4.Text;
            itm.Gift5 = txtGift5.Text;
            itm.Gift6 = txtGift6.Text;
            itm.Gift7 = txtGift7.Text;
            itm.Gift8 = txtGift8.Text;

            itm.SalesFormUpdatedAt = DateTime.Now;

            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                if (hdId.Text == "-1")
                {
                    if (Roles.IsUserInRole("agent"))
                    {
                        itm.AgentId = (Page as BasePage).CurrentUserId.Value;
                    }
                    else
                    {
                        using (var repoUser = RepositoryFactory.ResolveRepository<UserRepository>())
                        {
                            itm.AgentId = repoUser.AgentsCombo(false).First().Id;
                        }
                    }

                    newContactId = repo.InsertSalesForm(itm);
                }
                else
                {
                    itm.ContactId = Convert.ToInt32(hdId.Text);
                    repo.UpdateSalesForm(itm);
                }
            }
            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "SalesFormClose", "$('#salesFormDialog').dialog('close');", true);
            if (newContactId.HasValue)
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "SalesFormNewClientReopen", string.Format("createUpdateForm({0});", newContactId.Value.ToString()), true);

            (this.Page as BaseDataPage).LoadData();


        }

        protected void btnContracts_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("ContactManagementContracts.aspx?c={0}", hdId.Text), true);
        }
    }
}